//
//  CardDetailViewController.m
//  Guazi
//
//  Created by koolearn on 11-6-3.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "CardDetailViewController.h"
#import "ImageStore.h"
#import "GuaziAppDelegate.h"
#import "CardEditViewController.h"
#import "OperationLog.h"
#import "DataUploadService.h"


@implementation CardDetailViewController


@synthesize nameLabel;
@synthesize companyLabel;
@synthesize positionLabel;
@synthesize addressLabel;
@synthesize mobileLabel;
@synthesize telLabel;
@synthesize faxLabel;
@synthesize emailLabel;
@synthesize postcodeLabel;
@synthesize photoImage;
@synthesize deleteButton;
@synthesize card;

- (UIImage*)getProfileImage
{
    NSString* url = card.user.profileImageUrl_s;
	if ( url == nil ) {
		return [ImageStore defaultProfileImage:NO];
	}
    
    ImageStore *store = [GuaziAppDelegate getAppDelegate].imageStore;
	
    _imageReceiver.imageContainer = self;
    UIImage *image = [store getProfileImage:url isLarge:NO delegate:_imageReceiver];
    return image;
}


- (void)updateImage:(UIImage*)image
{
	photoImage.image = image;
    [self.view setNeedsDisplay];
    [self.view setNeedsLayout];    
}


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
	}
    return self;
}


- (id) initWithCard:(Card*)aCard
{
    self = [super init];
    if ( self ) {
        self.card = aCard;
    }
    return self;
}


- (void)dealloc
{
    [_imageReceiver release];
    [[GuaziAppDelegate getAppDelegate].imageStore removeDelegate:self forURL:card.user.profileImageUrl_s];

    [nameLabel release];
    [companyLabel release];
    [positionLabel release];
    [addressLabel release];
    [mobileLabel release];
    [telLabel release];
    [faxLabel release];
    [emailLabel release];
    [postcodeLabel release];
    [photoImage release];
	[deleteButton release];
    [card release];
    
    [super dealloc];
}


- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}


#pragma mark - View lifecycle

- (void) buildBarButtonItem
{
    self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemEdit target:self action:@selector(edit)] autorelease];
	self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(returnToMyCardList)] autorelease];
}


- (void) edit
{
    Card* c = [Card cardWithCard:card];
    CardEditViewController* controller = [[CardEditViewController alloc] initWithCard:c style:UITableViewStyleGrouped];
    [self.navigationController pushViewController:controller animated:YES];
    [controller release];
}


- (void) returnToMyCardList
{
	MyCardsViewController* controller = [[GuaziAppDelegate getAppDelegate] myCardsViewController];
	if ( controller ) {
		[controller refreshModifyCard:card];
	}
	
	[self.navigationController popViewControllerAnimated:YES];
}


- (void)viewDidLoad
{
    [super viewDidLoad];
	
    [self buildBarButtonItem];
    self.navigationItem.title = @"名片详情";

	UIImage *image = [UIImage imageNamed:@"deleteButton.png"];
	UIImage *imagePressed = [UIImage imageNamed:@"deleteButton_pressed.png"];
    
	[deleteButton setBackgroundImage:[image stretchableImageWithLeftCapWidth:7 topCapHeight:0] forState:UIControlStateNormal];
	[deleteButton setBackgroundImage:[imagePressed stretchableImageWithLeftCapWidth:7 topCapHeight:0] forState:UIControlStateHighlighted];
	deleteButton.titleLabel.text = @"删  除";
}


- (void) viewWillAppear:(BOOL)animated
{
	Card* c = [Card cardWithId:card.cardId];
	self.card = c;
	
    self.nameLabel.text = card.name;
    self.companyLabel.text = card.company;
    self.addressLabel.text = card.address;
    self.mobileLabel.text = card.mobile;
    self.telLabel.text = card.tel;
    self.faxLabel.text = card.fax;
    self.emailLabel.text = card.email;
    self.postcodeLabel.text = card.postcode;
    self.positionLabel.text = card.position;
    _imageReceiver = [[ImageStoreReceiver alloc] init];
    self.photoImage.image = [self getProfileImage];
    
	
	[super viewWillAppear:animated];
}


- (void) delete
{
	UIActionSheet* sheet = [[UIActionSheet alloc] initWithTitle:@"是否确认删除这张名片？" 
													   delegate:self 
											  cancelButtonTitle:@"取消" 
										 destructiveButtonTitle:@"确认" otherButtonTitles:nil];
	[sheet showInView:[GuaziAppDelegate getAppDelegate].tabBarController.view];
	[sheet release];
}


- (void) actionSheet:(UIActionSheet*)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex
{
	if ( buttonIndex == 0 ) {
		[card deleteDB];
        
        long long ownerId = [GuaziAppDelegate getAppDelegate].user.userId;
        OperationLog* log = [[OperationLog alloc] initWithModule:kOperationLogModuleCard 
                                                       operation:kOperationLogOperationDelete 
                                                           refId:[NSString stringWithFormat:@"%lld", ownerId] 
                                                          params:[NSString stringWithFormat:@"{cardId:'%lld'}", card.cardId]];
        [log insert];
        [log release];
        [[DataUploadService sharedInstance] run];
        
		//refresh
		MyCardsViewController* controller = [[GuaziAppDelegate getAppDelegate] myCardsViewController];
		if ( controller ) {
			[controller refreshDeleteCard:card];
		}
		
		[self.navigationController popViewControllerAnimated:YES];
	}
}


- (void)viewDidUnload
{
    [super viewDidUnload];
    [_imageReceiver release];
    [[GuaziAppDelegate getAppDelegate].imageStore removeDelegate:self forURL:card.user.profileImageUrl_s];

    self.nameLabel = nil;
    self.companyLabel = nil;
    self.positionLabel = nil;
    self.addressLabel = nil;
    self.mobileLabel = nil;
    self.telLabel = nil;
    self.faxLabel = nil;
    self.emailLabel = nil;
    self.postcodeLabel = nil;
    self.photoImage = nil;
	self.deleteButton = nil;
    self.card = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
